package gui;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

import BoBai.DanhSachBoBaiDaSX;
import Chat.ChatForServer;
import Chat.ThreadNhanTinHieuChat2;

public class ThreadLangNghe extends Thread {

	public Connect gui;
	public ServerSocket ls;

	
	public static int soluongclient = 0;
	public ThreadLangNghe( ServerSocket ss, Connect cc)
	{
		setName("Server Listen Thread");
		
		gui = cc;
		ls = ss;
	}
	
	public void run() {		
		System.out.println("Bat dau lang nghe ...");
		
		while(true) {
			Socket as;
			
			if(soluongclient < 5){
				try {
					// Wait for new subscribers
					as = ls.accept();
					
					// receive subscriber's service port
					DataInputStream dis = new DataInputStream(as.getInputStream());
					int portService = dis.readInt();
					
					ClientInfo ci = new ClientInfo(as, portService);
					
					
					ci.announceSocket = new Socket(as.getInetAddress().getHostAddress(), portService); 
					ci.chatSocket = new Socket(as.getInetAddress().getHostAddress(), portService);	
					
					

					gui.mht.addRow(ci);
											
					if(ci.threadNhanTHChat == null)
					{
						ci.threadNhanTHChat = new ThreadNhanTinHieuChat2(ci);
						ci.threadNhanTHChat.start();
					}

					soluongclient++;
					
				} catch (IOException e) {
					if(!ls.isClosed()) {
						try {
							ls.close();
						} catch (IOException e1) {
							e1.printStackTrace();
						}
					}
					System.out.println("Error: from accept connection (listen socket)!");
					System.out.println("Listen Thread was stopped!");
					break;
				}
			}
			
		}
	}

	public void interrupt() {
		if(!ls.isClosed()) {
			try {
				ls.close();
				System.out.println("Listen Socket was closed!");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	
}
